package org.example.service;


import org.example.model.Experiment;
import org.example.model.ExperimentStats;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

public class ChartGenerator {
    public static byte[] generateSubmissionRateChart(Map<Experiment, ExperimentStats> experimentStatsMap) throws IOException {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        for (Map.Entry<Experiment, ExperimentStats> entry : experimentStatsMap.entrySet()) {
            Experiment experiment = entry.getKey();
            ExperimentStats stats = entry.getValue();
            dataset.addValue(stats.getSubmissionRate(), "提交率", experiment.getName());
        }

        JFreeChart chart = ChartFactory.createLineChart(
                "实验提交率分析",
                "实验",
                "提交率 (%)",
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false
        );

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ChartUtils.writeChartAsPNG(outputStream, chart, 800, 600);
            return outputStream.toByteArray();
        }
    }
}
